package com.seestech.sell.web.report;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.utils.JsonUtils;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.common.utils.StringUtils;
import com.seestech.sell.domain.model.Agent;
import com.seestech.sell.domain.model.Goods;
import com.seestech.sell.domain.model.Recorder;
import com.seestech.sell.domain.model.User;
import com.seestech.sell.service.IAgentService;
import com.seestech.sell.service.IGoodsService;
import com.seestech.sell.service.IRecorderService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by idiot on 2017/6/22.
 */
@Controller
@RequestMapping(value = "stock")
public class StockController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(StockController.class);

    @Resource
    private IRecorderService recorderService;
    @Resource
    private IAgentService agentService;
    @Resource
    private IGoodsService goodsService;

    //加载page页面
    @RequiresPermissions(value = "order:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(Model model){
        logger.info("加载库存信息页面信息=====》》》");
        return "stock/page";
    }

    //加载data页面
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, Recorder info, Model model){
        User user = getUser();
        if(user == null){
            logger.error("【终端库存页面数据】======>>>>>>>>用户信息失效，请重新登录");
            return ResponseUtils.responseError("用户信息失效，请重新登录");
        }
        Page<Recorder> lists = recorderService.getRecorders(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", lists);
        return "stock/data";
    }

    /**
     * @description  根据终端编号获取商品剩余库存信息
     * @param agentId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getRemainStocks.json")
    public Object getRemainStocks(Long agentId){
        //根据终端编号获取终端信息
        Agent agent = agentService.getAgentByAgentId(agentId);
        if(agent != null){
            //根据终端id获取终端的库存信息
            Map<String, Object> map = agentService.getGoodsInfo(agent.getAgentId());
            if(map != null && map.size() > 0){
                String[] stocks = String.valueOf(map.get("stocks")).split(";");
                String[] alrams = String.valueOf(map.get("alarms")).split(";");
                String[] remains = String.valueOf(map.get("remain")).split(";");
                if(map.get("remain") == null){
                    remains = new String[]{};
                }
                int[] remain = StringUtils.toIntArray(remains, stocks.length);
                //获取商品编号
                String[] goodsIds = String.valueOf(map.get("products")).split(";");
                List<Goods> goodses = goodsService.getGoodsByGoodsIds(goodsIds);
                for (int i = 0; i < goodses.size(); i++) {
                    Goods goods = goodses.get(i);
                    goods.setRemain(String.valueOf(remain[i]));
                    goods.setStock(stocks[i]);
                    goods.setAlarm(alrams[i]);
                }
                return JSON.toJSON(JsonUtils.parseArray(goodses));
            }
        }
        return null;
    }

    /**
     * @description  根据终端编号获取商品剩余库存信息
     * @param agentIds   [{"23423"},{"1231356"}]
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAgentsStocks.json")
    public Object getAgentsStocks(String agentIds){
        List<Long> ids = JSON.parseArray(agentIds, Long.class);
        List<Goods> goodsList = new ArrayList<>();
        //根据终端id获取终端的库存信息
        List<Map<String, Object>> list = agentService.getGoodsInfoByIds(ids);
        if(list != null && list.size() > 0){
            for (Map map : list){
                //获取终端商品信息   库存   告警  剩余量
                String[] stocks = String.valueOf(map.get("stocks")).split(";");
                // String[] alrams = String.valueOf(map.get("alarms")).split(";");
                String[] remains = String.valueOf(map.get("remain")).split(";");
                if(map.get("remain") == null){
                    remains = new String[]{};
                }
                int[] remain = StringUtils.toIntArray(remains, stocks.length);
                //获取商品编号
                String[] goodsIds = String.valueOf(map.get("products")).split(";");
                List<Goods> goodses = goodsService.getGoodsByGoodsIds(goodsIds);
                for (int i = 0; i < goodses.size(); i++) {
                    Goods goods = goodses.get(i);
                    goods.setRemain(String.valueOf(remain[i]));
                    goods.setStock(stocks[i]);
                    // goods.setAlarm(alrams[i]);
                }
                goodsList.addAll(goodses);
            }
            return JSON.toJSON(JsonUtils.parseArray(goodsList));
        }else return null;
    }


    //删除品牌信息
    @RecordLog(value = "删除库存信息")
    @RequestMapping(value = "{recorderId}/delete", method = RequestMethod.POST)
    public void delete(@PathVariable("recorderId") Long recorderId){
        recorderService.delete(recorderId);
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"删除库存信息成功");
    }

    //批量删除
    @RequestMapping(value = "deleteBatch", method = RequestMethod.POST)
    public void deleteBatch(@RequestParam("ids[]") Long[] recorderIds){
        recorderService.deleteBatch(recorderIds);
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"批量删除库存信息成功");
    }
}
